Impact of Macroeconomic Factors on P&G Stock Price
Consumer staple funds are mutual funds or exchange-traded funds (ETFs) that invest in companies that produce essential goods and services, such as food, beverages, household products, and personal care items. These funds are designed to provide investors with stable and consistent returns, even in uncertain market conditions.
One of the top companies in the consumer staple sector is Procter & Gamble Co. (PG), which produces a wide range of products including personal care, cleaning, and food and beverage items. To analyze the stock price behavior of Procter & Gamble, an ARIMAX+ARCH/GARCH model can be employed.
By using an ARIMAX+ARCH/GARCH model to analyze the stock price behavior of Procter & Gamble, we can gain insights into how macroeconomic factors impact the company’s performance. For example, an increase in GDP growth rate or a decrease in unemployment rate may lead to increased consumer spending and a rise in Procter & Gamble’s stock price. Conversely, an increase in inflation or interest rates may lead to a decrease in consumer spending and a decline in Procter & Gamble’s stock price.
Time series Plot
Code
# get data
options("getSymbols.warning4.0"=FALSE)
options("getSymbols.yahoo.warning"=FALSE)
data.info = getSymbols("PG",src='yahoo', from = '2010-01-01',to = "2023-03-01",auto.assign = FALSE)
data = getSymbols("PG",src='yahoo', from = '2010-01-01',to = "2023-03-01")
df <- data.frame(Date=index(PG),coredata(PG))
# create Bollinger Bands
bbands <- BBands(PG[,c("PG.High","PG.Low","PG.Close")])
# join and subset data
df <- subset(cbind(df, data.frame(bbands[,1:3])), Date >= "2010-01-01")
# colors column for increasing and decreasing
for (i in 1:length(df[,1])) {
if (df$PG.Close[i] >= df$PG.Open[i]) {
df$direction[i] = 'Increasing'
} else {
df$direction[i] = 'Decreasing'
}
}
i <- list(line = list(color = '#43A098'))
d <- list(line = list(color = '#7F7F7F'))
# plot candlestick chart
fig <- df %>% plot_ly(x = ~Date, type="candlestick",
open = ~PG.Open, close = ~PG.Close,
high = ~PG.High, low = ~PG.Low, name = "PG",
increasing = i, decreasing = d)
fig <- fig %>% add_lines(x = ~Date, y = ~up , name = "B Bands",
line = list(color = '#ccc', width = 0.5),
legendgroup = "Bollinger Bands",
hoverinfo = "none", inherit = F)
fig <- fig %>% add_lines(x = ~Date, y = ~dn, name = "B Bands",
line = list(color = '#ccc', width = 0.5),
legendgroup = "Bollinger Bands", inherit = F,
showlegend = FALSE, hoverinfo = "none")
fig <- fig %>% add_lines(x = ~Date, y = ~mavg, name = "Mv Avg",
line = list(color = '#C052B3', width = 0.5),
hoverinfo = "none", inherit = F)
fig <- fig %>% layout(yaxis = list(title = "Price"))
# plot volume bar chart
fig2 <- df
fig2 <- fig2 %>% plot_ly(x=~Date, y=~PG.Volume, type='bar', name = "PG Volume",
color = ~direction, colors = c('#43A098','#7F7F7F'))
fig2 <- fig2 %>% layout(yaxis = list(title = "Volume"))
# create rangeselector buttons
rs <- list(visible = TRUE, x = 0.5, y = -0.055,
xanchor = 'center', yref = 'paper',
font = list(size = 9),
buttons = list(
list(count=1,
label='RESET',
step='all'),
list(count=3,
label='3 YR',
step='year',
stepmode='backward'),
list(count=1,
label='1 YR',
step='year',
stepmode='backward'),
list(count=1,
label='1 MO',
step='month',
stepmode='backward')
))
# subplot with shared x axis
fig <- subplot(fig, fig2, heights = c(0.7,0.2), nrows=2,
shareX = TRUE, titleY = TRUE)
fig <- fig %>% layout(title = paste("P&G Stock Price: January 2010 - March 2023"),
xaxis = list(rangeselector = rs),
legend = list(orientation = 'h', x = 0.5, y = 1,
xanchor = 'center', yref = 'paper',
font = list(size = 10),
bgcolor = 'transparent'))
figCode
log(data.info$`PG.Adjusted`) %>% diff() %>% chartSeries(theme=chartTheme('white'),up.col='#43A098')Code
#import the data
gdp <- read.csv("DATA/RAW DATA/gdp-growth.csv")
#change date format
gdp$Date <- as.Date(gdp$DATE , "%m/%d/%Y")
#drop DATE column
gdp <- subset(gdp, select = -c(1))
#export the cleaned data
gdp_clean <- gdp
write.csv(gdp_clean, "DATA/CLEANED DATA/gdp_clean_data.csv", row.names=FALSE)
#plot gdp growth rate
fig <- plot_ly(gdp, x = ~Date, y = ~value, type = 'scatter', mode = 'lines',line = list(color = 'rgb(240, 128, 128)'))
fig <- fig %>% layout(title = "U.S GPD Growth Rate: 2010 - 2022",xaxis = list(title = "Time"),yaxis = list(title ="GDP Growth Rate"))
figCode
#import the data
inflation_rate <- read.csv("DATA/RAW DATA/inflation-rate.csv")
#cleaning the data
#remove unwanted columns
inflation_rate_clean <- subset(inflation_rate, select = -c(1,HALF1,HALF2))
#convert the data to time series data
inflation_data_ts <- ts(as.vector(t(as.matrix(inflation_rate_clean))), start=c(2010,1), end=c(2023,2), frequency=12)
#export the data
write.csv(inflation_rate_clean, "DATA/CLEANED DATA/inflation_rate_clean_data.csv", row.names=FALSE)
#plot inflation rate
fig <- autoplot(inflation_data_ts, ylab = "Inflation Rate", color="#FFA07A")+ggtitle("U.S Inflation Rate: January 2010 - February 2023")+theme_bw()
ggplotly(fig)Code
#import the data
interest_data <- read.csv("DATA/RAW DATA/interest-rate.csv")
#change date format
interest_data$Date <- as.Date(interest_data$Date , "%m/%d/%Y")
#export the cleaned data
interest_clean_data <- interest_data
write.csv(interest_clean_data, "DATA/CLEANED DATA/interest_rate_clean_data.csv", row.names=FALSE)
#plot interest rate
fig <- plot_ly(interest_data, x = ~Date, y = ~value, type = 'scatter', mode = 'lines',line = list(color='rgb(219, 112, 147)'))
fig <- fig %>% layout(title = "U.S Interest Rate: January 2010 - March 2023",xaxis = list(title = "Time"),yaxis = list(title ="Interest Rate"))
figCode
#import the data
unemployment_rate <- read.csv("DATA/RAW DATA/unemployment-rate.csv")
#change date format
unemployment_rate$Date <- as.Date(unemployment_rate$Date , "%m/%d/%Y")
# export the data
write.csv(unemployment_rate, "DATA/CLEANED DATA/unemployment_rate_clean_data.csv", row.names=FALSE)
#plot unemployment rate
fig <- plot_ly(unemployment_rate, x = ~Date, y = ~Value, type = 'scatter', mode = 'lines',line = list(color = 'rgb(189, 183, 107)'))
fig <- fig %>% layout(title = "U.S Unemployment Rate: January 2010 - March 2023",xaxis = list(title = "Time"),yaxis = list(title ="Unemployment Rate"))
figThe stock price of P&G experienced a steady increase from 2010 to 2014, likely due to the company’s strong financial performance and consistent dividend payouts. However, from 2014 to 2016, P&G’s stock price experienced a decline, which could be attributed to a combination of factors such as slowing sales growth and increased competition in the consumer goods industry.
Following this period of steadiness and decline, P&G’s stock price began to recover from 2016 to 2018, likely due to the company’s efforts to streamline its operations and focus on core brands. This trend continued into 2019, with P&G’s stock price reaching an all-time high in mid-2019.
However, the outbreak of the COVID-19 pandemic in early 2020 caused a brief dip in P&G’s stock price, as investors were uncertain about the impact of the pandemic on the company’s operations and financial performance. Nevertheless, P&G’s strong position in the consumer goods industry and its ability to adapt to changing market conditions helped it to quickly rebound and continue its growth trend throughout 2020 and into early 2021.
Since early 2021, P&G’s stock price has experienced some volatility, likely due to a combination of factors such as global economic uncertainty and fluctuations in consumer demand for the company’s products.
As discussed before, the macroeconomic factors of GDP growth, inflation, interest rates, and unemployment rate are closely interrelated and play a crucial role in the overall health and stability of an economy. From 2010 to 2023, the global economy experienced a mix of ups and downs, with periods of strong GDP growth followed by slowdowns and recessions.
The second plot shows the first difference of the logarithm of the adjusted P&G stock price. Taking the first difference removes any long-term trends and transforms the time series into a stationary process. From the plot, we can observe that the first difference of the logarithm of the P&G stock price appears to be stationary, as the mean and variance are roughly constant over time.
Enodogenous and Exogenous Variables
Code
numeric_data <- c("PG.Adjusted","gdp", "interest", "inflation", "unemployment")
numeric_data <- final[, numeric_data]
normalized_data_numeric <- scale(numeric_data)
normalized_data <- ts(normalized_data_numeric, start = c(2010, 1), end = c(2021,10),frequency = 4)
ts_plot(normalized_data,
title = "Normalized Time Series Data for PG Stock and Macroeconomic Variables",
Ytitle = "Normalized Values",
Xtitle = "Year")Code
# Get upper triangle of the correlation matrix
get_upper_tri <- function(cormat){
cormat[lower.tri(cormat)]<- NA
return(cormat)
}
cormat <- round(cor(normalized_data_numeric),2)
upper_tri <- get_upper_tri(cormat)
melted_cormat <- melt(upper_tri, na.rm = TRUE)
# Create a ggheatmap
ggheatmap <- ggplot(melted_cormat, aes(Var2, Var1, fill = value))+
geom_tile(color = "white")+
scale_fill_gradient2(low = "blue", high = "red", mid = "white",
midpoint = 0, limit = c(-1,1), space = "Lab",
name="Pearson\nCorrelation") +
theme_minimal()+ # minimal theme
theme(axis.text.x = element_text(angle = 45, vjust = 1,
size = 12, hjust = 1))+
coord_fixed()
ggheatmap +
geom_text(aes(Var2, Var1, label = value), color = "black", size = 4) +
theme(
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.ticks = element_blank(),
legend.justification = c(1, 0),
legend.position = c(0.6, 0.7),
legend.direction = "horizontal")+
guides(fill = guide_colorbar(barwidth = 7, barheight = 1,
title.position = "top", title.hjust = 0.5))Code
par(mfrow=c(1,1))
ccf_result <- ccf(normalized_data[, c("PG.Adjusted")], normalized_data[, c("gdp")],
lag.max = 300,
main = "Cros-Correlation Plot for PG Stock Price and GDP Growth Rate ",
ylab = "CCF")Code
cat("The sum of cross correlation function is", sum(abs(ccf_result$acf)))The sum of cross correlation function is 4.8926
Code
par(mfrow=c(1,1))
ccf_result <- ccf(normalized_data[, c("PG.Adjusted")], normalized_data[, c("interest")],
lag.max = 300,
main = "Cros-Correlation Plot for PG Stock Price and Interest Rate",
ylab = "CCF")Code
cat("The sum of cross correlation function is", sum(abs(ccf_result$acf)))The sum of cross correlation function is 12.00986
Code
par(mfrow=c(1,1))
ccf_result <- ccf(normalized_data[, c("PG.Adjusted")], normalized_data[, c("inflation")],
lag.max = 300,
main = "Cros-Correlation Plot for PG Stock Price and Inflation Rate",
ylab = "CCF")Code
cat("The sum of cross correlation function is", sum(abs(ccf_result$acf)))The sum of cross correlation function is 15.81772
Code
par(mfrow=c(1,1))
ccf_result <- ccf(normalized_data[, c("PG.Adjusted")], normalized_data[, c("unemployment")],
lag.max = 300,
main = "Cros-Correlation Plot for PG Stock Priceand Unemployment Rate",
ylab = "CCF")Code
cat("The sum of cross correlation function is", sum(abs(ccf_result$acf)))The sum of cross correlation function is 19.34548
The Normalized Time Series Data for Stock Price and Macroeconomic Variables plot shows the same variables as the first plot but has been normalized to a common range of 0 to 1 using the scale() function in R, which standardizes the variables to have a mean of 0 and a standard deviation of 1. The heatmap analysis of the normalized data reveals that inflation and unemployment rate exhibit strong positive correlations with the stock price indices, indicating that these variables may significantly influence stock price movements. On the other hand, weaker correlations were observed between the stock price indices and GDP and interest rates, suggesting that these variables may have less impact on stock price fluctuations. The cross-correlation feature plots confirm these findings, indicating that inflation and unemployment rate are more suitable feature variables for the ARIMAX model when predicting P&G movements.
Final Exogenous variables: Macroeconomic indicators: Inflation rate and unemployment rate.
Enodogenous and Exogenous Variables Plot
Code
final_data <- final %>%dplyr::select( Date,PG.Adjusted, inflation,unemployment)
numeric_data <- c("PG.Adjusted", "inflation","unemployment")
numeric_data <- final_data[, numeric_data]
normalized_data_numeric <- scale(numeric_data)
normalized_numeric_df <- data.frame(normalized_data_numeric)
normalized_data_ts <- ts(normalized_data_numeric, start = c(2010, 1), frequency = 4)
autoplot(normalized_data_ts, facets=TRUE) +
xlab("Year") + ylab("") +
ggtitle("P&G Stock Price, Inflation Rate and Unemployment Rate in USA 2010-2023")Code
# Convert your multivariate time series data to a matrix
final_data_ts_multivariate <- as.matrix(normalized_data_ts)
# Check for stationarity using Phillips-Perron test
phillips_perron_test <- ur.pp(final_data_ts_multivariate)
summary(phillips_perron_test)
##################################
# Phillips-Perron Unit Root Test #
##################################
Test regression with intercept
Call:
lm(formula = y ~ y.l1)
Residuals:
Min 1Q Median 3Q Max
-1.7824 -0.1562 -0.0531 0.0989 4.4953
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.001564 0.040861 0.038 0.97
y.l1 0.859052 0.041275 20.813 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.5087 on 153 degrees of freedom
Multiple R-squared: 0.739, Adjusted R-squared: 0.7373
F-statistic: 433.2 on 1 and 153 DF, p-value: < 2.2e-16
Value of test-statistic, type: Z-alpha is: -23.2156
aux. Z statistics
Z-tau-mu 0.0386
The results of the Phillips-Perron unit root test indicate strong evidence against the null hypothesis of a unit root, as the p-value for the coefficient of the lagged variable is less than the significance level of 0.05. This suggests that the variable y, which is being tested for stationarity, is likely stationary. Furthermore, the test statistic Z-tau-mu is 0.0386, which is smaller than the critical value of Z-alpha (-23.2156), providing further evidence of stationarity.
To determine whether the linear model requires an ARCH model, an ARCH test is conducted. The ACF and PACF plots are also used to identify suitable model values.
Model Fitting
Code
normalized_numeric_df$PG.Adjusted<-ts(normalized_numeric_df$PG.Adjusted,star=decimal_date(as.Date("2010-01-01",format = "%Y-%m-%d")),frequency = 4)
normalized_numeric_df$inflation<-ts(normalized_numeric_df$inflation,star=decimal_date(as.Date("2010-01-01",format = "%Y-%m-%d")),frequency = 4)
normalized_numeric_df$unemployment<-ts(normalized_numeric_df$unemployment,star=decimal_date(as.Date("2010-01-01",format = "%Y-%m-%d")),frequency = 4)
fit <- lm(PG.Adjusted ~ inflation+unemployment, data=normalized_numeric_df)
fit.res<-ts(residuals(fit),star=decimal_date(as.Date("2010-01-01",format = "%Y-%m-%d")),frequency = 4)
############## Then look at the residuals ############
returns <- fit.res %>% diff()
autoplot(returns)+ggtitle("Linear Model Returns")Code
byd.archTest <- ArchTest(fit.res, lags = 1, demean = TRUE)
byd.archTest
ARCH LM-test; Null hypothesis: no ARCH effects
data: fit.res
Chi-squared = 33.303, df = 1, p-value = 7.885e-09
Code
ggAcf(returns) +ggtitle("ACF for returns")Code
ggPacf(returns) +ggtitle("PACF for returns")The ARCH LM-test was conducted with the null hypothesis of no ARCH effects. The test resulted in a chi-squared value of 33.303 with one degree of freedom, and a very low p-value of 7.885e-09. This suggests strong evidence against the null hypothesis, indicating the presence of ARCH effects in the data.
Based on the ACF and PACF plots, it appears that there is some significant autocorrelation and partial autocorrelation at multiple lags, which suggests that an ARIMA model may not be sufficient to capture the time series behavior. Additionally, the values for p and q appear to be relatively high, with p = 8 and q = 8 being suggested by the plots.
ARIMAX Model
Code
xreg <- cbind(Inflation = normalized_data_ts[, "inflation"],
Unemployment = normalized_data_ts[, "unemployment"])
fit.auto <- auto.arima(normalized_data_ts[, "PG.Adjusted"], xreg = xreg)
summary(fit.auto)Series: normalized_data_ts[, "PG.Adjusted"]
Regression with ARIMA(0,1,0) errors
Coefficients:
drift Inflation Unemployment
0.0442 0.0139 -0.1199
s.e. 0.0271 0.0857 0.0381
sigma^2 = 0.03803: log likelihood = 12.55
AIC=-17.1 AICc=-16.23 BIC=-9.38
Training set error measures:
ME RMSE MAE MPE MAPE MASE
Training set -1.921084e-05 0.1873552 0.1337598 409.0784 430.9485 0.4244207
ACF1
Training set 0.1245825
Code
checkresiduals(fit.auto)
Ljung-Box test
data: Residuals from Regression with ARIMA(0,1,0) errors
Q* = 12.832, df = 8, p-value = 0.1177
Model df: 0. Total lags used: 8
Code
ARIMA.c=function(p1,q1,q2,data){
temp=c()
d=1
i=1
temp= data.frame()
ls=matrix(rep(NA,6*30),nrow=30)
for (p in p1)#
{
for(q in q1:q2)#
{
for(d in 0:1)
{
if(p+d+q<=6)
{
model<- Arima(data,order=c(p,d,q))
ls[i,]= c(p,d,q,model$aic,model$bic,model$aicc)
i=i+1
#print(i)
}
}
}
}
temp= as.data.frame(ls)
names(temp)= c("p","d","q","AIC","BIC","AICc")
temp
}
output <- ARIMA.c(1,1,8,data=residuals(fit))
output[which.min(output$AIC),] p d q AIC BIC AICc
2 1 1 1 19.41045 25.20592 19.92108
Code
output[which.min(output$BIC),] p d q AIC BIC AICc
2 1 1 1 19.41045 25.20592 19.92108
Code
output[which.min(output$AICc),] p d q AIC BIC AICc
2 1 1 1 19.41045 25.20592 19.92108
Code
set.seed(1234)
model_output <- capture.output(sarima(fit.res, 1,1,1)) Code
cat(model_output[30:61], model_output[length(model_output)], sep = "\n")$fit
Call:
arima(x = xdata, order = c(p, d, q), seasonal = list(order = c(P, D, Q), period = S),
xreg = constant, transform.pars = trans, fixed = fixed, optim.control = list(trace = trc,
REPORT = 1, reltol = tol))
Coefficients:
ar1 ma1 constant
0.5118 -0.2678 -0.0053
s.e. 0.3621 0.3920 0.0573
sigma^2 estimated as 0.07602: log likelihood = -6.7, aic = 21.4
$degrees_of_freedom
[1] 48
$ttable
Estimate SE t.value p.value
ar1 0.5118 0.3621 1.4137 0.1639
ma1 -0.2678 0.3920 -0.6833 0.4977
constant -0.0053 0.0573 -0.0933 0.9261
$AIC
[1] 0.4196416
$AICc
[1] 0.4296541
$BIC
[1] 0.5711574
Code
n=length(fit.res)
k= 51
rmse1 <- matrix(NA, (n-k),4)
rmse2 <- matrix(NA, (n-k),4)
rmse3 <- matrix(NA, (n-k),4)
st <- tsp(fit.res)[1]+(k-5)/4
for(i in 1:(n-k))
{
xtrain <- window(fit.res, end=st + i/4)
xtest <- window(fit.res, start=st + (i+1)/4, end=st + (i+4)/4)
#ARIMA(0,1,0) ARIMA(1,1,1)
fit <- Arima(xtrain, order=c(0,1,0),
include.drift=TRUE, method="ML")
fcast <- forecast(fit, h=4)
fit2 <- Arima(xtrain, order=c(1,1,1),
include.drift=TRUE, method="ML")
fcast2 <- forecast(fit2, h=4)
rmse1[i,1:length(xtest)] <- sqrt((fcast$mean-xtest)^2)
rmse2[i,1:length(xtest)] <- sqrt((fcast2$mean-xtest)^2)
}
plot(1:4,colMeans(rmse1,na.rm=TRUE), type="l",col=2, xlab="horizon", ylab="RMSE")
lines(1:4, colMeans(rmse2,na.rm=TRUE), type="l",col=3)
legend("topleft",legend=c("fit1","fit2"),col=2:4,lty=1)Based on the results of the auto.arima function, the suggested best model is ARIMA(0,1,0). However, when we manually test different ARIMA models, we find that ARIMA(1,1,1) has the lowest values for AIC, BIC, and AICC. Additionally, both models have similar standardized residual plots, with means close to 0, indicating a good fit. The ACF plot of residuals also shows no significant lags, further indicating a well-fitted model.
To determine the best model, we conduct cross-validation and compare the RMSE values of both models. The results show that ARIMA(1,1,1) has lower RMSE values than ARIMA(0,1,0), indicating that it is the better model.
We can then proceed to choose the best GARCH model using ARIMA(1,1,1) as the base model.
Squared Residuals
Code
fit <- lm(PG.Adjusted ~ inflation+unemployment, data=normalized_numeric_df)
fit.res<-ts(residuals(fit),star=decimal_date(as.Date("2010-01-01",format = "%Y-%m-%d")),frequency = 4)
fit <- Arima(fit.res,order=c(1,1,1))
res=fit$res
plot(res^2,main='Squared Residuals')Code
acf(res^2,24, main = "ACF Residuals Square")Code
pacf(res^2,24, main = "PACF Residuals Square")From the squared residuals of the best ARIMA model, it can be observed that the ACF plot and PACF plot indicate that the residuals are not autocorrelated and are white noise, indicating a good fit of the model. Based on the squared residuals of the best ARIMA model, we can see that the ACF and PACF plots indicate that most of the values lie between the blue lines. Additionally, the p-value is 2 and q-value is 2. This suggests that the model has a good fit and that there is no significant autocorrelation or partial autocorrelation in the residuals. Now we can proceed by fitting GARCH Model for p and q values.
GARCH Model
Code
model <- list() ## set counter
cc <- 1
for (p in 1:2) {
for (q in 1:2) {
model[[cc]] <- garch(res,order=c(q,p),trace=F)
cc <- cc + 1
}
}
## get AIC values for model evaluation
GARCH_AIC <- sapply(model, AIC) ## model with lowest AIC is the best
which(GARCH_AIC == min(GARCH_AIC))[1] 4
Code
model[[which(GARCH_AIC == min(GARCH_AIC))]]
Call:
garch(x = res, order = c(q, p), trace = F)
Coefficient(s):
a0 a1 a2 b1 b2
2.257e-02 3.047e-02 3.867e-01 1.788e-15 1.963e-01
Code
summary(garchFit(~garch(1,1),res, trace=F))
Title:
GARCH Modelling
Call:
garchFit(formula = ~garch(1, 1), data = res, trace = F)
Mean and Variance Equation:
data ~ garch(1, 1)
<environment: 0x121395940>
[data = res]
Conditional Distribution:
norm
Coefficient(s):
mu omega alpha1 beta1
-0.00046672 0.00001929 0.14787443 0.90106994
Std. Errors:
based on Hessian
Error Analysis:
Estimate Std. Error t value Pr(>|t|)
mu -4.667e-04 3.139e-02 -0.015 0.988
omega 1.929e-05 4.754e-03 0.004 0.997
alpha1 1.479e-01 9.919e-02 1.491 0.136
beta1 9.011e-01 1.030e-01 8.746 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Log Likelihood:
-3.885086 normalized: -0.07471318
Description:
Tue Jan 9 20:59:52 2024 by user:
Standardised Residuals Tests:
Statistic p-Value
Jarque-Bera Test R Chi^2 1.93484 0.3800624
Shapiro-Wilk Test R W 0.9777844 0.436524
Ljung-Box Test R Q(10) 9.637902 0.4728146
Ljung-Box Test R Q(15) 15.96454 0.3844124
Ljung-Box Test R Q(20) 27.64276 0.1181294
Ljung-Box Test R^2 Q(10) 27.23887 0.002387006
Ljung-Box Test R^2 Q(15) 45.57051 6.220836e-05
Ljung-Box Test R^2 Q(20) 51.54644 0.0001325434
LM Arch Test R TR^2 28.74873 0.004292744
Information Criterion Statistics:
AIC BIC SIC HQIC
0.3032725 0.4533682 0.2925272 0.3608157
Code
summary(garchFit(~garch(2,1),res, trace=F))
Title:
GARCH Modelling
Call:
garchFit(formula = ~garch(2, 1), data = res, trace = F)
Mean and Variance Equation:
data ~ garch(2, 1)
<environment: 0x121a3a008>
[data = res]
Conditional Distribution:
norm
Coefficient(s):
mu omega alpha1 alpha2 beta1
-0.01258591 0.00315889 0.00000001 0.23548224 0.76820639
Std. Errors:
based on Hessian
Error Analysis:
Estimate Std. Error t value Pr(>|t|)
mu -1.259e-02 3.345e-02 -0.376 0.70674
omega 3.159e-03 6.361e-03 0.497 0.61945
alpha1 1.000e-08 1.290e-01 0.000 1.00000
alpha2 2.355e-01 1.984e-01 1.187 0.23522
beta1 7.682e-01 2.043e-01 3.760 0.00017 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Log Likelihood:
-2.5769 normalized: -0.04955577
Description:
Tue Jan 9 20:59:52 2024 by user:
Standardised Residuals Tests:
Statistic p-Value
Jarque-Bera Test R Chi^2 0.889059 0.6411259
Shapiro-Wilk Test R W 0.9811742 0.57696
Ljung-Box Test R Q(10) 9.405694 0.4940824
Ljung-Box Test R Q(15) 15.23843 0.4343829
Ljung-Box Test R Q(20) 26.4125 0.1526163
Ljung-Box Test R^2 Q(10) 23.65166 0.008580658
Ljung-Box Test R^2 Q(15) 42.63577 0.0001793075
Ljung-Box Test R^2 Q(20) 50.08643 0.0002152542
LM Arch Test R TR^2 26.23072 0.009955126
Information Criterion Statistics:
AIC BIC SIC HQIC
0.2914192 0.4790388 0.2750022 0.3633482
Code
summary(garchFit(~garch(1,2),res, trace=F))
Title:
GARCH Modelling
Call:
garchFit(formula = ~garch(1, 2), data = res, trace = F)
Mean and Variance Equation:
data ~ garch(1, 2)
<environment: 0x1121e7ed0>
[data = res]
Conditional Distribution:
norm
Coefficient(s):
mu omega alpha1 beta1 beta2
-0.00103294 0.00049633 0.14694869 0.89300883 0.00000001
Std. Errors:
based on Hessian
Error Analysis:
Estimate Std. Error t value Pr(>|t|)
mu -1.033e-03 3.265e-02 -0.032 0.975
omega 4.963e-04 5.285e-03 0.094 0.925
alpha1 1.469e-01 1.622e-01 0.906 0.365
beta1 8.930e-01 1.440e+00 0.620 0.535
beta2 1.000e-08 1.394e+00 0.000 1.000
Log Likelihood:
-4.088505 normalized: -0.0786251
Description:
Tue Jan 9 20:59:52 2024 by user:
Standardised Residuals Tests:
Statistic p-Value
Jarque-Bera Test R Chi^2 2.312217 0.3147084
Shapiro-Wilk Test R W 0.9763827 0.385689
Ljung-Box Test R Q(10) 9.746995 0.4629638
Ljung-Box Test R Q(15) 16.04255 0.3792292
Ljung-Box Test R Q(20) 27.41625 0.1239541
Ljung-Box Test R^2 Q(10) 27.39288 0.002256282
Ljung-Box Test R^2 Q(15) 44.98822 7.6901e-05
Ljung-Box Test R^2 Q(20) 50.7473 0.0001729734
LM Arch Test R TR^2 29.18193 0.0037021
Information Criterion Statistics:
AIC BIC SIC HQIC
0.3495579 0.5371775 0.3331409 0.4214868
Based on the analysis of the different GARCH models, it appears that GARCH(1,1) is the optimal choice. Although the AIC values of the different models are relatively similar, we can further evaluate their significance to make a final determination. Upon closer inspection, it appears that GARCH(1,1) has significantly better values than the other models, indicating that it is the most appropriate choice. Therefore, we can conclude that the GARCH(1,1) model is the best fit for the data.
Best Model
Code
#fiting an ARIMA model to the Inflation variable
inflation_fit<-auto.arima(normalized_numeric_df$inflation)
finflation<-forecast(inflation_fit)
#fitting an ARIMA model to the Unemployment variable
unemployment_fit<-auto.arima(normalized_numeric_df$unemployment)
funemployment<-forecast(unemployment_fit)
# best model fit for forcasting
xreg <- cbind(Inflation = normalized_data_ts[, "inflation"],
Unemployment = normalized_data_ts[, "unemployment"])
summary(arima.fit<-Arima(normalized_data_ts[, "PG.Adjusted"],order=c(1,1,1),xreg=xreg),include.drift = TRUE)Series: normalized_data_ts[, "PG.Adjusted"]
Regression with ARIMA(1,1,1) errors
Coefficients:
ar1 ma1 Inflation Unemployment
0.3380 -0.1329 0.0428 -0.1152
s.e. 0.4362 0.4426 0.0897 0.0383
sigma^2 = 0.03922: log likelihood = 12.27
AIC=-14.55 AICc=-13.21 BIC=-4.89
Training set error measures:
ME RMSE MAE MPE MAPE MASE
Training set 0.02921537 0.1882886 0.1408886 283.0815 316.01 0.4470403
ACF1
Training set -0.03829399
Code
summary(final.fit <- garchFit(~garch(1,1), res,trace = F))
Title:
GARCH Modelling
Call:
garchFit(formula = ~garch(1, 1), data = res, trace = F)
Mean and Variance Equation:
data ~ garch(1, 1)
<environment: 0x1110af3f0>
[data = res]
Conditional Distribution:
norm
Coefficient(s):
mu omega alpha1 beta1
-0.00046672 0.00001929 0.14787443 0.90106994
Std. Errors:
based on Hessian
Error Analysis:
Estimate Std. Error t value Pr(>|t|)
mu -4.667e-04 3.139e-02 -0.015 0.988
omega 1.929e-05 4.754e-03 0.004 0.997
alpha1 1.479e-01 9.919e-02 1.491 0.136
beta1 9.011e-01 1.030e-01 8.746 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Log Likelihood:
-3.885086 normalized: -0.07471318
Description:
Tue Jan 9 20:59:53 2024 by user:
Standardised Residuals Tests:
Statistic p-Value
Jarque-Bera Test R Chi^2 1.93484 0.3800624
Shapiro-Wilk Test R W 0.9777844 0.436524
Ljung-Box Test R Q(10) 9.637902 0.4728146
Ljung-Box Test R Q(15) 15.96454 0.3844124
Ljung-Box Test R Q(20) 27.64276 0.1181294
Ljung-Box Test R^2 Q(10) 27.23887 0.002387006
Ljung-Box Test R^2 Q(15) 45.57051 6.220836e-05
Ljung-Box Test R^2 Q(20) 51.54644 0.0001325434
LM Arch Test R TR^2 28.74873 0.004292744
Information Criterion Statistics:
AIC BIC SIC HQIC
0.3032725 0.4533682 0.2925272 0.3608157
Code
ht <- final.fit@h.t #a numeric vector with the conditional variances (h.t = sigma.t^delta)
#############################
data=data.frame(final)
data$Date<-as.Date(data$Date,"%Y-%m-%d")
data2= data.frame(ht,data$Date)
ggplot(data2, aes(y = ht, x = data.Date)) + geom_line(col = '#43A098') + ylab('Conditional Variance') + xlab('Date')From the ARIMA(1,1,1), we see that the training set error measures also suggest a good fit, with low mean absolute error, root mean squared error, and autocorrelation of the residuals. GATCH(1,1) model model is used to estimate the volatility of the standardized residuals of the previous regression model. The model includes a mean equation that estimates the mean of the residuals and a variance equation that models the conditional variance of the residuals. The coefficients of the mean equation suggest that the mean of the residuals is close to zero. The variance equation coefficients suggest that the conditional variance of the residuals is dependent on the past conditional variances and the past squared standardized residuals. The model’s log-likelihood value is -3.885, and the AIC, BIC, SIC, and HQIC values are all relatively low, indicating a good fit of the model. The standardized residuals tests indicate that the residuals are approximately normally distributed and that there is no significant autocorrelation in the residuals.
The volatility of the model seems high in 2020 but has decreased gradually in the past few months. This could indicate that the asset’s price was experiencing a lot of fluctuations in 2020, but the market has stabilized recently.
Model Diagnostics
Code
fit2<-garch(res,order=c(1,1),trace=F)
checkresiduals(fit2) Code
qqnorm(fit2$residuals, pch = 1)
qqline(fit2$residuals, col = "blue", lwd = 2)Code
Box.test (fit2$residuals, type = "Ljung")
Box-Ljung test
data: fit2$residuals
X-squared = 0.020613, df = 1, p-value = 0.8858
The ACF plot of the residuals shows all the values between the blue lines, which indicates that the residuals are not significantly autocorrelated. The range of values for the residual plot between -2 and 2 is considered acceptable. Additionally, the QQ plot of the residuals shows a linear plot on the line, which is another good indication that the residuals are normally distributed. The QQ plot is a valuable tool to assess if the residuals follow a normal distribution, and in this case, the plot suggests that the residuals do indeed follow a normal distribution.
The Box-Ljung test, a p-value of 0.9008 indicates that the model’s residuals are not significantly autocorrelated, meaning that the model has captured most of the information in the data. This result is good because it suggests that the model is a good fit for the data and has accounted for most of the underlying patterns in the data. Therefore, we can rely on the model’s predictions and use them to make informed decisions.
Forecast
Code
predict(final.fit, n.ahead = 5, plot=TRUE) meanForecast meanError standardDeviation lowerInterval upperInterval
1 -0.0004667176 0.4689872 0.4689872 -0.9196648 0.9187314
2 -0.0004667176 0.4803474 0.4803474 -0.9419302 0.9409968
3 -0.0004667176 0.4919817 0.4919817 -0.9647331 0.9637997
4 -0.0004667176 0.5038969 0.5038969 -0.9880864 0.9871530
5 -0.0004667176 0.5160997 0.5160997 -1.0120036 1.0110701
The forecasted plot is based on the best model ARIMAX(1,1,1)+GARCH(1,1). This model takes into account the autoregressive and moving average components of the data, as well as the impact of exogenous variables on the time series. Additionally, the GARCH component of the model accounts for the volatility clustering in the data. Overall, this model is well-suited to make accurate predictions about future values of the time series.
Equation of the Model
The equation of the ARIMAX(1,1,1) model is:
\(Y(t) = c + \phi_1(Y{(t-1)} - X{(t-1)}) + \theta_1\epsilon{(t-1)} + \epsilon(t)\)
where, \(Y(t)\) is the time series variable, \(X(t-1)\) is the exogenous variable, \(c\) is a constant, \(\phi_1\) and \(\theta_1\) are the parameters, and \(\epsilon(t)\) is the error term.
The equation of the GARCH(1,1) model is:
\(\sigma^2(t) = \alpha_0+\alpha_1\epsilon_t^2(t-1)+ \beta_1\sigma^2(t-1)\)
where \(\sigma^2_t\) is the conditional variance at time \(t\), \(\alpha_0\) is a constant, \(\alpha_1\) and \(\beta_1\) are the parameters, and \(\epsilon_t\) is the error term.
The combined equation of the ARIMAX(1,1,1)+GARCH(1,1) model is:
\(Y(t) = c + \phi_1(Y(t-1) - X(t-1)) + \theta_1\epsilon(t-1) + \epsilon(t)\)
\(\epsilon(t) = \sigma(t) * \epsilon~(t)\)
\(\sigma^2(t) = \alpha_0+\alpha_1\epsilon_t^2(t-1)+ \beta_1\sigma^2(t-1)\)